import React, { PureComponent } from 'react';
import { Button, Card } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import _ from 'lodash';
import ProjectsPath from '@/components/ProjectsPath';
import PageEmpty from '@/components/PageEmpty';
import PageTop from './components/PageTop';
import qs from 'qs';
import YearsRender from './components/YearsRender';
import CurrentStage from './components/CurrentStage';
import { BaseTable, utils } from '@/components/BaseTable';
import { getTitleTree, getFixedColumns } from './utils/publicMethod';
import AuthorizedButton from '@/components/AuthorizedButton';

// 全盘回款计划
@connect(state => ({
  ...state.AllReturnMoneyPlan,
  orgStructure: state.orgStructure,
}))
export default class PriceManage extends PureComponent {
  state = { emptyMsg: '' };

  componentDidMount() {
    const { match } = this.props;
    this.fetchOverAllYears({ projectId: match.params.project });
  }

  componentWillReceiveProps(nextProps) {
    const { match } = this.props;
    // match变动
    const isProjectId = match.params.project !== nextProps.match.params.project;
    // 切换年
    const changeYear = nextProps.currentYear !== this.props.currentYear;
    if (isProjectId) this.fetchOverAllYears({ projectId: nextProps.match.params.project });
    if (nextProps.currentYear && changeYear) this.getItems(nextProps);
  }

  // 请求表格数据
  getItems = props => {
    const { dispatch, currentYear, match } = props;
    const self = this;
    self.setState({ emptyMsg: '' });
    dispatch({
      type: 'AllReturnMoneyPlan/getTableList',
      payload: {
        params: {
          projectId: match.params.project,
          year: currentYear,
        },
      },
      callback: () => self.setState({ emptyMsg: '暂无全盘回款计划数据' }),
    });
  };

  // 获取年份列表
  fetchOverAllYears = ({ projectId }) => {
    const { dispatch } = this.props;
    const self = this;
    self.setState({ emptyMsg: '' });
    dispatch({
      type: 'AllReturnMoneyPlan/getYearList',
      payload: { params: { projectId } },
      callback: () => self.setState({ emptyMsg: '暂无全盘回款计划数据' }),
    });
  };

  // 导出全盘报表
  handleExportReportForm = () => {
    const { match } = this.props;
    const params = {
      projectId: match.params.project,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    window.open(
      `${process.env.apiUrl}/api/v1/returnPlan/returnOverallPlanVersionExport?${exportQueryString}`,
    );
  };

  render() {
    const { overAllYears, currentYear, currentMonths, expandedRowKeys, treeData } = this.props;
    let titleTree = [];
    let fixedColumns = [];
    if (currentYear && !_.isEmpty(overAllYears)) {
      titleTree = getTitleTree(currentYear, currentMonths);
      fixedColumns = getFixedColumns(currentYear, currentMonths);
    }
    const headerRenderer = utils.getHeaderRenderer(titleTree, 4, () => (
      <YearsRender {...this.props} />
    ));
    return (
      <PageHeaderWrapper
        className="page-header"
        breadcrumb={null}
        title={<ProjectsPath menu="SupplyPlan" {...this.props} />}
        tags={<CurrentStage {...this.props} />}
        extra={
          <AuthorizedButton authority="business_returnMoneyPlan_allExportReport">
            <Button
              className="yellow-button"
              onClick={this.handleExportReportForm}
              disabled={_.isEmpty(treeData)}
            >
              导出报表
            </Button>
          </AuthorizedButton>
        }
      >
        <Card className="page-header-card" bordered={false}>
          {!_.isEmpty(currentYear) && <PageTop {...this.props} />}
          {!_.isEmpty(currentYear) && !_.isEmpty(treeData) ? (
            <BaseTable
              subtractHeight="165px"
              defaultExpandedRowKeys={expandedRowKeys}
              expandColumnKey="name"
              headerHeight={[30, 30, 30, 30, 30]}
              fixedColumns={fixedColumns}
              headerRenderer={headerRenderer}
              treeData={treeData}
            />
          ) : (
            <PageEmpty emptyTitle={this.state.emptyMsg} />
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }
}
